import requests
import json
import os

# API配置
BASE_URL = "http://localhost:8001"
ANALYZE_ENDPOINT = f"{BASE_URL}/analyze_recording"

def test_with_audio_file(audio_file_path):
    """使用指定音频文件测试API"""
    print(f"\n🎵 测试音频文件: {audio_file_path}")
    
    if not os.path.exists(audio_file_path):
        print(f"❌ 文件不存在: {audio_file_path}")
        return False
    
    try:
        # 准备文件
        with open(audio_file_path, 'rb') as audio_file:
            files = {'Record_file': (os.path.basename(audio_file_path), audio_file)}
            
            print("📤 正在上传文件...")
            response = requests.post(ANALYZE_ENDPOINT, files=files)
            
            print(f"📊 状态码: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                print("\n✅ 分析成功！结果如下:")
                print("-" * 50)
                for key, value in result.items():
                    print(f"{key}: {value}")
                print("-" * 50)
                return True
            else:
                print(f"❌ 请求失败: {response.text}")
                return False
                
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        return False

def quick_test():
    """快速测试API服务"""
    print("🚀 快速API测试")
    print(f"🌐 目标服务: {BASE_URL}")
    
    # 1. 测试服务是否运行
    try:
        response = requests.get(f"{BASE_URL}/health", timeout=5)
        if response.status_code == 200:
            print("✅ API服务运行正常")
        else:
            print(f"⚠️  API服务状态异常: {response.status_code}")
    except Exception as e:
        print(f"❌ 无法连接到API服务: {e}")
        print("请确保API服务已启动 (python api_server.py)")
        return False
    
    # 2. 查找音频文件
    audio_extensions = ['.wav', '.mp3', '.m4a', '.flac', '.aac']
    audio_files = []
    
    for file in os.listdir('.'):
        if any(file.lower().endswith(ext) for ext in audio_extensions):
            audio_files.append(file)
    
    if not audio_files:
        print("⚠️  当前目录下没有找到音频文件")
        print(f"支持的格式: {', '.join(audio_extensions)}")
        return False
    
    print(f"📁 找到 {len(audio_files)} 个音频文件: {audio_files}")
    
    # 3. 测试第一个音频文件
    success = test_with_audio_file(audio_files[0])
    
    if success:
        print("\n🎉 测试完成！API工作正常。")
    else:
        print("\n❌ 测试失败，请检查API服务。")
    
    return success

if __name__ == "__main__":
    # 如果提供了命令行参数，使用指定的音频文件
    import sys
    if len(sys.argv) > 1:
        audio_file = sys.argv[1]
        print(f"使用指定的音频文件: {audio_file}")
        success = test_with_audio_file(audio_file)
    else:
        success = quick_test()
    
    exit(0 if success else 1)